/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cqrcb.cloud;

import com.alibaba.cloud.dubbo.annotation.DubboTransported;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lengleng
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringCloudApplication
@EnableAutoConfiguration
@EnableAsync(proxyTargetClass = true)
public class QuotaControlApplication {



	@Autowired
	@LoadBalanced
	private RestTemplate restTemplate;

	public static void main(String[] args) {
		SpringApplication.run(QuotaControlApplication.class, args);
	}

	@Bean
	@LoadBalanced
	@DubboTransported
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	@PostConstruct
	private void init() {
		initDegradeRule();
		instanceFlowRules();
	}

	private static void initDegradeRule() {
		List<DegradeRule> rules = new ArrayList<>();
		DegradeRule rule = new DegradeRule();
		rule.setResource("customSentinel");
		// set threshold rt, 10 ms
		rule.setCount(30);
		rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
		rule.setTimeWindow(10);
		rules.add(rule);
		DegradeRuleManager.loadRules(rules);
	}

	private static void instanceFlowRules() {
		List<FlowRule> list = new ArrayList<>();
		FlowRule flowRule = new FlowRule();
		flowRule.setResource("customSentinel");
		flowRule.setCount(2);
		flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		list.add(flowRule);
		FlowRuleManager.loadRules(list);
	}

}
